package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;

import com.tanhua.dubbo.service.TimeLineService;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private IdWorker idWorker;

    @Override
    public void publish(Movement movement) {
        try {
            //1.保存动态详情
            //设置Pid
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            //保存数据
            mongoTemplate.save(movement);
            //2.查询当前用户的好友数据
            /*Criteria criteria = Criteria.where("userId").is(movement.getUserId());
            Query query = new Query(criteria);
            List<Friend> friends = mongoTemplate.find(query,Friend.class);
            //3.循环好友，构建时间线数据存入数据库
            for (Friend friend : friends) {
                MovementTimeLine timeLine = new MovementTimeLine();
                timeLine.setMovementId(movement.getId());
                timeLine.setCreated(System.currentTimeMillis());
                timeLine.setUserId(friend.getUserId());
                timeLine.setFriendId(friend.getFriendId());
                mongoTemplate.save(timeLine);
            }
            //忽略事务处理*/
            timeLineService.saveTimeLine(movement.getUserId(), movement.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        //创建Critical
        Criteria criteria = Criteria.where("userId").is(userId);
        //创建Query对象
        Query query = Query.query(criteria);
        //查询总记录数
        //Long count = mongoTemplate.count(query,Movement.class);
        //设置分页查询参数
        query.skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //查询分页数据列表
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        //构造返回值
        return new PageResult(page, pagesize, 0L, list);
    }

    @Override
    public PageResult findByUserId(Long userId, Integer state, Integer page, Integer pagesize) {
        Query query = new Query();
        if (userId != null){
            query.addCriteria(Criteria.where("userId").is(userId));
        }
        if (state != null){
            query.addCriteria(Criteria.where("state").is(state));
        }
        //查询总数
        Long count = mongoTemplate.count(query,Movement.class);
        query.skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> list = mongoTemplate.find(query,Movement.class);
        return new PageResult(page,pagesize,count,list);
    }

    /**
     * 查询用户好友发布的所有动态
     *
     * @param page
     * @param pagesize
     * @param friendId 当前操作用户id
     * @return
     */
    @Override
    public List<Movement> findFriendMovements(Integer page, Integer pagesize, Long friendId) {
        //1.根据friendId查询时间线表
        Query query = Query.query(Criteria.where("friendId").is(friendId))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> lineList = mongoTemplate.find(query,MovementTimeLine.class);
        //2.提取动态id列表
        List<ObjectId> list = CollUtil.getFieldValues(lineList,"movementId",ObjectId.class);
        //3.根据动态id查询动态详情
        Query movementQuery = Query.query(Criteria.where("id").in(list));
        return mongoTemplate.find(movementQuery,Movement.class);
    }

    //随机查询多条数据
    @Override
    public List<Movement> randomMovements(Integer counts) {
        //1.创建统计对象，设置统计参数
        TypedAggregation<Movement> aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(counts));
        //2.调用mongoTemplate方法统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation,Movement.class);
        //3.获取统计结果
        return results.getMappedResults();
    }

    //根据pids查询
    @Override
    public List<Movement> findMovementsByPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query,Movement.class);
    }

    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId,Movement.class);
    }

    @Override
    public void update(String movementId, Integer state) {
        Query query = Query.query(Criteria.where("id").in(new ObjectId(movementId)));
        Update update = Update.update("state", state);
        mongoTemplate.updateFirst(query, update, Movement.class);
    }
}
